import Service from '../../core/baseService';

import { deleteNullOrUndefinedField } from '../../utils/index';
// import { pickBy as _pickBy, identity as _identity } from 'lodash'

export default class UserService extends Service {
  public groupModel;
  constructor(ctx) {
    super(ctx);

    this.ctx = ctx;
    this.model = ctx.model.AuthUser;
    this.groupModel = ctx.model.AuthGroup;
  }

  async list(page = 1, pageSize = 20, query) {
    let list: any[] = [];
    let total = 0;

    const queryParams = {
      where: deleteNullOrUndefinedField(query),
      include: [
        { model: this.ctx.model.AuthGroup }
      ],
      order: [['id', 'DESC']],
    };
    if (Object.keys(query).length === 0) {
      Object.assign(queryParams, {
        offset: (Number(page) - 1) * pageSize,
        limit: pageSize,
      });
    }

    const result: any = await this.model
            .findAndCountAll(queryParams);

    list = result.rows;
    total = result.count;
    return {
      list,
      total,
      page,
      pageSize,
    };
  }

  async create(data) {
    const { config } = this.ctx.app;
    const result = await this.model.create(
      Object.assign(data, {
        password: this.ctx.helper.md5(`${config.saltPassword}${data.password}`),
      }),
    );

    return result;
  }

  async destroy(id) {

    const result = await this.model.destroy({ where: { id } });
    // 删除用户组集合中与此用户相关的数据
    await this.ctx.model.AuthUserGroup.destroy({ where: { user_id: id } });
    return result;
  }

  async getUserById(id) {
    const result = await this.model.findOne({
      where: { id }
    });

    return result;
  }

  async update(id, data) {
    let newData = Object.assign(data, { _id: id });

    const { config } = this.ctx.app;
    if (data.password) {
      newData = Object.assign(newData, {
        password: this.ctx.helper.md5(`${config.saltPassword}${data.password}`),
      });
    }

    try {
      return await this.model.update(
        newData,
        {
          where: {
            id
          }
        }
      )
    } catch (err: any) {
      this.ctx.logger.error(err.message);
      return '';
    }
  }

  async findOne(account) {
    const result = await this.model.findOne({ account });
    return result;
  }

  async getUser(query) {
    return this.model.findOne(query);
  }
}
